import MTypes from "../../store/types/TypesMutation"

/**
 * 查询产品公共数据，主要包括分类、标签和系统尺码定义，查询到的数据保存到页面内存
 * @param self 页面
 * @param categoryList 页面分类控件数据，用于回调函数
 * @param types 查询数据类型列表
 * @param isForce 是否强制到后台查询
 * @param afterFun 回调函数
 */
export const getProductCommonData = (self, categoryList, types, isForce, afterFun) => {
  let actualTypes = [];
  if(isForce){
    actualTypes = types;
  } else { //非强制更新的时候如果存储中没有的就到后台查询
    for(let type of types) {
      switch (type) {
      case 1: // 产品尺码信息
        if(self.$store.getters.product.allSysSize.length <= 0){
          actualTypes.push(type);
        }
        break;
      case 2: //角标
        if(self.$store.getters.product.allTabs.length <= 0){
          actualTypes.push(type);
        }
        break;
      case 3: //分类
        if(self.$store.getters.product.classifications.length <= 0){
          actualTypes.push(type);
        }
        break;
      case 4: //后台管理标签
        if(self.$store.getters.product.allManageTabs.length <= 0){
          actualTypes.push(type);
        }
        break;
      default:
        break;
      }
    }
  }

  if(actualTypes.length > 0){
    self.$apiProduct.getCommonData(actualTypes)
      .then(function (response) {
        if (response.success) {
          let result = response.result;
          for(let type of actualTypes){
            switch(type){
              case 1: // 产品尺码信息
                let allSysSize = {};
                for(let key in result.allSysSize){
                  allSysSize[key]= result.allSysSize[key];
                }
                self.$store.commit(MTypes.product.storeSysSize, allSysSize);
                break;
              case 2: //标签
                let tabs = [];
                result.allTabs.forEach(
                  function (item) {
                    tabs.push(item);
                  }
                );
                self.$store.commit(MTypes.product.storeTabs, tabs);
                break;
              case 3: //分类
                let classifictionts = [];
                result.allClassification.forEach(function(item){
                  if(item.state === 1){
                    item.name = item.name + "(未启用)";
                  }
                  if(item.isPlaceholder){
                    item.name = item.name + "(占位分类)";
                  }
                  classifictionts.push(item);
                });
                self.$store.commit(MTypes.product.storeClassifications, classifictionts);
                break;
              case 4: //后台管理标签
                let allManageTabs = [];
                result.allManageTabs.forEach(function (item){
                  allManageTabs.push(item);
                });
                self.$store.commit(MTypes.product.storeManageTabs, allManageTabs);
                break;
              default:
                break;
            }
          }
        } else {
          self.$Message.error(response.errorMessage);
        }
      });
  }

  if(afterFun){
    afterFun(self, categoryList);
  }
};


/**
 * 创建分类下拉菜单（主要用于查询条件）
 * @param self 页面
 * @param categoryList 存放分类的页面数据
 */
export const createCategoryList = (self, categoryList) => {
  let classifications = self.$store.getters.product.classifications;
  categoryList.splice(0, categoryList.length);
  let level1Resource = classifications.filter(category => category.level === 1);
  let level2Resource = classifications.filter(category => category.level === 2);
  let level3Resource = classifications.filter(category => category.level === 3);

  level1Resource.forEach(function(classificationLevel1){
    let dataLevel2 = [];
    level2Resource.filter(classification => classification.parentId == classificationLevel1.id).forEach(function (itemLevel2) {
      let dataLevel3 = [];
      level3Resource.filter(classification => classification.parentId == itemLevel2.id).forEach(function (itemLevel3) {
        dataLevel3.push({value: itemLevel3.id, label: itemLevel3.name,level:3});
      });
      dataLevel2.push({value: itemLevel2.id, label: itemLevel2.name,children: dataLevel3 ,level:2});

    });
    categoryList.push({value:classificationLevel1.id,label:classificationLevel1.name,children:dataLevel2,level:1});
  }) ;
};

/**
 * 创建分类下拉菜单（主要用于查询条件）
 * @param self 页面
 * @param categoryList 存放分类的页面数据
 */
export const createCategoryCascader = (self, categoryList) => {
  let classifications = self.$store.getters.product.classifications;
  categoryList.splice(0, categoryList.length);
  let level1Resource = classifications.filter(category => category.level === 1);
  let level2Resource = classifications.filter(category => category.level === 2);
  let level3Resource = classifications.filter(category => category.level === 3);

  level1Resource.forEach(function(classificationLevel1){
    let dataLevel2 = [];
    level2Resource.filter(classification => classification.parentId == classificationLevel1.id).forEach(function (itemLevel2) {
      let dataLevel3 = [];
      level3Resource.filter(classification => classification.parentId == itemLevel2.id).forEach(function (itemLevel3) {
        dataLevel3.push({value: itemLevel3.id, label: itemLevel3.name,level:3, disabled: itemLevel3.type==2});
      });
      dataLevel2.push({value: itemLevel2.id, label: itemLevel2.name,children: dataLevel3 ,level:2, disabled: itemLevel2.type==2});

    });
    categoryList.push({value:classificationLevel1.id,label:classificationLevel1.name,children:dataLevel2,level:1, disabled: classificationLevel1.type==2});
  }) ;
};

/**弹窗提示上传图片的尺寸大小
 * @param imageList 图片数组列表，格式为{name: "", url: ""}
 * */
export const imageSizeModal = (self, imageList) => {
  self.$Spin.show();
  let content = "";
  getImageSizeByUrls(imageList, 0, content,function (content) {
    // console.log(content);
    self.$Spin.hide();
    self.$Modal.info({
      title: "图片尺寸",
      content: "<table>"+content+"</table>"
    });
  })
}

/**批量循环通过url获取图片分尺寸
 * @param imageList 图片数组列表，格式为{name: "", url: ""}
 * @param imageIndex 当前图片在imageList中的索引位置
 * @param content 图片尺寸的描述，是多个表格行
 * @param callback 回调函数，用于最终返回尺寸描述信息
 * */
export const getImageSizeByUrls = (imageList, imageIndex, content, callback) => {
  if(imageIndex < imageList.length) {
      getImageSizeByUrl(imageList[imageIndex].url).then(res => {
        content += "<tr><td><span style='margin-right: 20px;'>"+imageList[imageIndex].name+"</span><br><span >尺寸(px): "+res+"</span></td></tr>";
        if(imageIndex < imageList.length-1) {
          getImageSizeByUrls(imageList, ++imageIndex, content, callback);
        }else{
          callback(content);
        }
      }).catch(error => {
        callback(error);
      });
  }else{
    callback(content);
  }
}

/**通过url获取图片尺寸大小
 * @param url 图片的url
 * @return 图片尺寸描述，格式为 width×height
 * */
export const getImageSizeByUrl = (url) => {
  return new Promise((resolve, reject) => {
    let image = document.createElement("img");
    image.src = url;
    if(image.complete) {
      let imageSize = image.width + "×" + image.height;
      resolve(imageSize);
    }else{
      image.onload = function () {
        let imageSize = image.width + "×" + image.height;
        resolve(imageSize);
      }
      image.onerror = function () {
        reject("加载图片失败！");
      }
    }
  });
}

/**通过文件获取图片的尺寸大小
 * @param file 图片的js文件对象
 * @return 图片尺寸描述，格式为 width×height
 * */
export const getImageSizeByFile = (file) => {
  return new Promise((resolve) => {
    let reader = new FileReader();
    reader.onload = function (e) {
      let image = document.createElement("img");
      image.src = e.target.result;
      image.onload = function () {
        let imageSize = image.width + "×" + image.height;
        resolve(imageSize);
      }
    };
    reader.readAsDataURL(file);
  });
}
// 计算文件大小函数(保留两位小数), Size为字节大小
export const getfilesize= function (size) {
  if (!size)
    return "0K";
  var num = 1024.00; //byte
  if (size < num)
    return size + "B";
  if (size < Math.pow(num, 2))
    return (size / num).toFixed(2) + "K"; //kb
  if (size < Math.pow(num, 3))
    return (size / Math.pow(num, 2)).toFixed(2) + "M"; //M
  if (size < Math.pow(num, 4))
    return (size / Math.pow(num, 3)).toFixed(2) + "G"; //G
  return (size / Math.pow(num, 4)).toFixed(2) + "T"; //T
}

/**判断字符串是否为空*/
export const isEmpty = (val) => {
  return val == null || val === "" || val == undefined;
}

/**判断字符串是否为空*/
export const isNotEmpty = (val) => {
  return !isEmpty(val);
}

/**
 * @param params text:要翻译的文本; caseType:首字母转换类型，0或空表示不变，1表示转为大写
 * */
export const translateText = (self, params, callback) => {
  self.$Spin.show();
  self.$apiOther.translateText(params).then(response => {
    self.$Spin.hide();
    if(response.success) {
      if(callback) {
        callback(response.result);
      }
    }else{
      self.$Message.error(response.errorMessage);
    }
  }).catch(() => {
    self.$Spin.hide();
    self.$Message.error("翻译失败！");
  })
}

/**是否含有电子邮箱地址*/
export const containsEmail = (text) => {
  if(text == null) {
    return false;
  }
  let reg = /[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+/g;
  return reg.test(text);
}

/**获取电子邮箱*/
export const getEmails = (text) => {
  if(text == null) {
    return [];
  }
  let reg = /[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+/g;
  return text.match(reg);
}
